package sword.T51;

/**
 * @Author: 18362
 * @Create: 2022-04-09 22:26:47 星期六
 */
class Solution {
    private int[] temp;
    private int res = 0;

    public int reversePairs(int[] nums) {
        temp = new int[nums.length];
        mergeSort(nums, 0, nums.length-1);
        return res;
    }

    private void mergeSort(int[] nums, int left, int right) {
        if (left >= right)
            return;
        int mid = (left + right) / 2;
        mergeSort(nums, left, mid);
        mergeSort(nums, mid+1, right);
        merge(nums, left, mid, right);
    }

    private void merge(int[] nums, int left, int mid, int right) {
        int i = left, j = mid + 1, k = left;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j])
                temp[k++] = nums[i++];
            else {
                temp[k++] = nums[j++];
                res += (mid + 1 - i);
            }
        }
        while (i <= mid) {
            temp[k++] = nums[i++];
        }
        while (j <= right) {
            temp[k++] = nums[j++];
        }
        for (i=left; i<=right; ++i)
            nums[i] = temp[i];
    }
}
